<template>
  <el-row justify="center" align="middle" class="wrap">
    <el-col :xs="22" :sm="14" :md="10" :lg="8" :xl="6">
      <el-card shadow="never" class="box">
        <template #header>
          <div class="card-header">新用户注册</div>
        </template>

        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px" @keyup.enter="handleSubmit">
          <el-form-item label="账号" prop="username">
            <el-input v-model.trim="form.username" placeholder="3~16 位字母/数字/下划线" maxlength="16" clearable />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" show-password placeholder="6~20 位大小写字母+数字+符号"
              maxlength="20" />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPwd">
            <el-input v-model="form.confirmPwd" type="password" show-password placeholder="请再次输入密码" maxlength="20" />
          </el-form-item>

          <el-form-item label="头像" prop="url">
            <el-upload :action="form.url" list-type="picture-card" :file-list="fileList"
              >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <!-- 添加上传按钮 -->
            <el-form-item style="margin-top: 10px;margin-left: 320px;">
              <el-button type="primary" @click="uploadHandler()">上传</el-button>
            </el-form-item>
          </el-form-item>
          <!-- <el-form-item label="验证码" prop="captcha">
            <el-input
              v-model.trim="form.captcha"
              placeholder="右侧点击图片刷新"
              maxlength="6"
            >
              <template #append>
                <img
                  :src="captchaUrl"
                  class="captcha"
                  @click="refreshCaptcha"
                  title="看不清？点击刷新"
                />
              </template>
            </el-input>
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" size="default" :loading="loading" @click="handleSubmit">立即注册</el-button>
            <el-button size="default" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="tip">
          已有账号？
          <el-link type="primary" :underline="false" @click="$router.push('/')">去登录</el-link>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

/* --------------------- 表单数据 --------------------- */
const ruleFormRef = ref()
const loading = ref(false)

const form = reactive({
  username: '',
  password: '',
  confirmPwd: '',
  url: '',
})

/* --------------------- 校验规则 --------------------- */
const equalToPassword = (rule, value, callback) => {
  if (value !== form.password) callback(new Error('两次输入密码不一致'))
  else callback()
}

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^\w{3,16}$/, message: '账号格式有误', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{6,20}$/,
      message: '需包含大小写字母、数字及特殊字符',
      trigger: 'blur'
    }
  ],
  confirmPwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: equalToPassword, trigger: 'blur' }
  ],
  //   captcha: [
  //     { required: true, message: '请输入验证码', trigger: 'blur' },
  //     { len: 6, message: '验证码为 6 位', trigger: 'blur' }
  //   ]
}

/* --------------------- 验证码 --------------------- */
// const captchaUrl = ref('/api/captcha?' + Date.now())
// function refreshCaptcha() {
//   captchaUrl.value = '/api/captcha?' + Date.now()
// }

/* --------------------- 提交 --------------------- */
async function handleSubmit() {
  await ruleFormRef.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    try {
      // 这里换成你的真实接口
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      }).then(r => r.json())

      if (res.code === 0) {
        ElMessage.success('注册成功，即将跳转登录页')
        setTimeout(() => location.replace('/'), 1500)
      } else {
        ElMessage.error(res.message || '注册失败')
        refreshCaptcha()
      }
    } catch (e) {
      ElMessage.error('网络错误')
    } finally {
      loading.value = false
    }
  })
}

function resetForm() {
  ruleFormRef.value.resetFields()
  refreshCaptcha()
}

</script>

<style scoped>
.wrap {
  min-height: 100vh;
  background-image: url("../assets/login-logo2.jpg");
}

.box {
  border-radius: 8px;
}

.card-header {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
}

.captcha {
  height: 32px;
  cursor: pointer;
  vertical-align: middle;
}

.tip {
  text-align: center;
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}
</style>